package com.totcy.atom.utils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.totcy.atom.BuildConfig;
import com.totcy.atom.MyApplication;
import com.totcy.atom.R;

import java.io.ByteArrayOutputStream;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;


/**
 * description : 微信分享工具类
 *
 * @author : Totcy
 * @date : 2018/1/10 19:09
 * @update : 2018/1/10
 */

public class WeChatShareUtils {

    //    分享或收藏的目标场景，通过修改scene场景值实现。
//    发送到聊天界面——WXSceneSession
//    发送到朋友圈——WXSceneTimeline
//    添加到微信收藏——WXSceneFavorite
    public static final int SHARE_SESSION = 1;
    public static final int SHARE_TIMELINE = 2;
    public static final int SHARE_FAVORITE = 3;

    private IWXAPI wxApi;
    private Activity activity;


    public WeChatShareUtils(Activity activity) {
        this.activity = activity;
        wxApi = WXAPIFactory.createWXAPI(MyApplication.getApplication(), BuildConfig.WX_APPID, true);
        wxApi.registerApp(BuildConfig.WX_APPID);
    }

    public void shareText() {

    }

    /**
     * 网页分享
     *
     * @param url
     * @param title
     * @param shareType
     */
    public void shareUrl(final String url, final String thumbUrl, final String title, final int shareType) {

        Observable.create(new ObservableOnSubscribe<WXMediaMessage>() {
            @Override
            public void subscribe(final ObservableEmitter<WXMediaMessage> e) throws Exception {
                WXWebpageObject webpageObject = new WXWebpageObject();
                webpageObject.webpageUrl = url;
                final WXMediaMessage mediaMessage = new WXMediaMessage(webpageObject);
                mediaMessage.title = title;
                mediaMessage.description = "";
                //缩列图处理
                if (!TextUtils.isEmpty(thumbUrl)) {
                    Glide.with(activity)
                            .asBitmap()
                            .load(thumbUrl)
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
                                    mediaMessage.thumbData = bmpToByteArray(bitmap);
                                    e.onNext(mediaMessage);
                                }
                            });
                } else {
                    Bitmap thumbData = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.ic_launcher_square);
                    mediaMessage.thumbData = bmpToByteArray(thumbData);
                    thumbData.recycle();
                    e.onNext(mediaMessage);
                }
            }
        }).unsubscribeOn(AndroidSchedulers.mainThread())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<WXMediaMessage>() {
                    @Override
                    public void accept(@NonNull WXMediaMessage mediaMessage) throws Exception {
                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                        req.transaction = "webPage";
                        req.message = mediaMessage;
                        req.scene = getShareType(shareType);
                        wxApi.sendReq(req);
                    }
                });
    }

    public void shareImage(final String imagePath, final int shareType) {
        Glide.with(activity)
                .asBitmap()
                .load(imagePath)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
                        WXImageObject imageObject = new WXImageObject(bitmap);
                        WXMediaMessage mediaMessage = new WXMediaMessage();
                        mediaMessage.mediaObject = imageObject;
                        //缩列图
                        mediaMessage.thumbData = bmpToByteArray(bitmap);

                        SendMessageToWX.Req req = new SendMessageToWX.Req();
                        req.transaction = "Image";
                        req.message = mediaMessage;
                        req.scene = getShareType(shareType);
                        wxApi.sendReq(req);

                    }
                });

    }

    private int getShareType(int type) {
        int result = SendMessageToWX.Req.WXSceneSession;
        switch (type) {

            case SHARE_SESSION:
                result = SendMessageToWX.Req.WXSceneSession;
                break;
            case SHARE_TIMELINE:
                result = SendMessageToWX.Req.WXSceneTimeline;
                break;
            case SHARE_FAVORITE:
                result = SendMessageToWX.Req.WXSceneFavorite;
                break;

        }
        return result;
    }

    /**
     * 控制微信分享图片缩列图大小
     *
     * @param bmp
     * @return
     */
    private byte[] bmpToByteArray(Bitmap bmp) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, output);
        int options = 100;
        //循环判断如果压缩后图片是否大于30kb,大于继续压缩
        while (output.toByteArray().length / 1024 > 30) {
            //重置baos即清空baos
            output.reset();
            //这里压缩options%，把压缩后的数据存放到baos中
            bmp.compress(Bitmap.CompressFormat.JPEG, options, output);
            //每次都减少10
            options -= 10;
        }
        //bmp.recycle();
        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
